<template>
  <div class="view">
    <el-row class="handle-box">
      <el-button
        class="jianbianbule"
        type="primary"
        icon="el-icon-plus"
        @click="handleAdd"
        >{{ $t("curveunitcon.curveunit") }}</el-button
      >
      <!-- {{this.getUserIP(ip)}} -->
    </el-row>
<div class="tablebox">
    <template>
      <el-table :data="tables" size="mini" stripe class="tablefisbox">
        <el-table-column type="index" :label="$t('public.number')" width="80">
        </el-table-column>
        <el-table-column prop="unitName" :label="$t('curvecon.unit')">
        </el-table-column>
        <el-table-column prop="remark" :label="$t('public.remark')">
        </el-table-column>
        <el-table-column prop="createUser" :label="$t('public.createUser')"></el-table-column>
        <el-table-column prop="createTime" :label="$t('public.createTime')" :formatter="carTimeFilter"> </el-table-column>
        <el-table-column :label="$t('public.operation')" width="250">
          <template slot-scope="scope">
            <el-button
              type="warning"
              icon="el-icon-edit"
              round
              size="mini"
              @click="handleEdit(scope.$index, scope.row)"
              >{{ $t("public.edit") }}</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              round
              size="mini"
              @click="handleDel(scope.$index, scope.row)"
              >{{ $t("public.del") }}</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </template>

    <!--工具条-->
		<el-col class="pages">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="pageSize"
          :total="total"
        >
        </el-pagination>
      </el-col>

    <!--编辑界面-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
			<el-form :model="editForm" :rules="editFormRules" ref="editForm">
        <el-form-item :label="$t('curveunitcon.unitName')" prop="unitName">
          <el-input v-model="editForm.unitName"></el-input>
        </el-form-item>
        <el-form-item :label="$t('public.remark')">
          <el-input v-model="editForm.remark"></el-input>
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
			 <el-button @click.native="dialogFormVisible=false" type="success">{{ $t("public.cancelbtn") }}</el-button>
			  <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">{{$t("public.savebtn")}}</el-button>
        <el-button v-else type="primary" @click="updateData">{{ $t("public.changebtn") }}</el-button>
			</div>
		</el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      dialogStatus: "", //编辑框界面切换
      textMap: {      //添加与编辑界面
        update: this.$t('public.edit'),
        create: this.$t('public.create')
      },
      dialogFormVisible: false,  //弹窗
      tables: [],  //表格数据
      total: 0, //总共条数
      page: 1,  //请求页
      limit: 10,  //页条数
      pageSize: 1, //当前页
      //是否必填项
      editFormRules: {
        unitName: [{ required: true, message: "请输入曲线单位", trigger: "blur" }],
      },
      //编辑界面数据
      editForm: {
        unitName: "",
      },
      options: [], //单位下拉列表
    };
  },
  mounted(){
    this.getUnit()
    this.unitSelect()
  },
  methods: {
    handleSizeChange(val) {
      this.limit = val;
      this.getUnit();
    },
    handleCurrentChange(val) {
      this.page = val;
      this.pageSize = val;
      this.getUnit();
    },
    //编辑参数
    handleEdit(index, row) {
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.editForm = {
        unitId:  row.unitId,
        unitName: row.unitName,
        remark: row.remark,
        createUser: JSON.parse(this.$store.state.userInfo).uid
      }
    },
    //新增参数
    handleAdd() {
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.editForm = {
        unitName: "",
        remark: "",
        createUser: JSON.parse(this.$store.state.userInfo).uid
      }
      
    },
    //获取
    async getUnit() {
      try {
        let params = {
          page: this.page,
          limit: this.limit,
        }
        let res = await this.$api.set.getUnit(params)
        this.total = res.count; 
        this.tables = res.data; 
      } catch (e) {
        console.log(e)
      }
    },
    //获取区域名称数据
    async unitSelect(){
      let option = await this.$api.set.unitSelect();
      this.options = option.data
    },
    //添加
    createData() {
      this.$refs.editForm.validate(async valid => {
        if (valid) {
          let params = Object.assign({}, this.editForm)
          let res = await this.$api.set.addUnit(params)
          if(res.code == 200){
            this.$message({
              message: this.$t('public.addsuccess'),
              type: "success"
            });
            this.$refs["editForm"].resetFields(); //清空表单
            this.dialogFormVisible = false; //关闭弹窗
            this.getUnit(); //刷新数据
          }else{
            this.$message({
              showClose: true,
              message: res.msg,
              type: "error"
            });
          } 
        }
      });
    },
    //修改
     updateData() {
      this.$refs.editForm.validate(async valid => {
        if (valid) {
          let params = Object.assign({}, this.editForm)
          let res = await this.$api.set.editUnit(params)
          if(res.code == 200){
            this.$message({
              message: this.$t('public.editsuccess'),
              type: "success"
            });
            this.$refs["editForm"].resetFields(); //清空表单
              this.dialogFormVisible = false;
            this.getUnit(); //刷新数据
          }else{
            this.$message({
              showClose: true,
              message: res.msg,
              type: "error"
            });
          }
        }
      });
    },
    //删除
    handleDel(index, row) {
      // 二次确认删除
      this.$confirm(this.$t('public.confirmcontent'), this.$t('public.confirmtitle'), {
        type: "warning",
      })
      .then(async () => {
        let params = {
          id: row.unitId,
          usid: JSON.parse(this.$store.state.userInfo).uid
        }
        let res = await this.$api.set.removeUnit(params)
        if(res.code == 200){
          this.$message.success(this.$t('public.confirmtips1'));
          this.getUnit(); //刷新数据
        }else {
            this.$message({
              showClose: true,
              message: res.msg,
              type: "error",
            });
          }
      })
      .catch(() => {});
    },
    carTimeFilter(row, column, cellValue, index) {
        const daterc = row[column.property]
        if(daterc !=null){
          return this.$moment(daterc).format("YYYY-MM-DD HH:mm:ss")
        }
    },
    getUserIP(onNewIP) { //  onNewIp - your listener function for new IPs
       //compatibility for firefox and chrome
       var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
       var pc = new myPeerConnection({
          iceServers: []
      }),
      noop = function() {},
      localIPs = {},
      ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g,
      key;
  
      function iterateIP(ip) {
          if (!localIPs[ip]) onNewIP(ip);
          localIPs[ip] = true;
     }
  
       //create a bogus data channel
      pc.createDataChannel("");
  
      // create offer and set local description
      pc.createOffer().then(function(sdp) {
          sdp.sdp.split('\n').forEach(function(line) {
              if (line.indexOf('candidate') < 0) return;
              line.match(ipRegex).forEach(iterateIP);
          });
          
          pc.setLocalDescription(sdp, noop, noop);
      }).catch(function(reason) {
          // An error occurred, so handle the failure to connect
      });
  
      //sten for candidate events
      pc.onicecandidate = function(ice) {
          if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
          ice.candidate.candidate.match(ipRegex).forEach(iterateIP);
      };
  }
  },
};
</script>